import React, { Component } from 'react'

//  hoc :包装用户表单，增加数据管理能力，校验
function kFormCreate(Comp) {
    return class extends Component {
        constructor(props) {
            super(props)
            this.options = {} //字段选项设置
            this.state = {}   //各字段值
        }

        // 处理表单输入事件
        handleChange = (e) => {
            const { name, value } = e.target
            this.setState({ [name]: value }, () => {
                // 数值变化后在校验
                this.validaateField(name)
            })

        }

        // 移入
        handleFocus = (e) => {
            const field = e.target.name
            this.setState({ [field + 'Focus']: true })
        }

        // 表单项校验
        validaateField = (field) => {
            // 写到这里
            const rules = this.options[field].rules;
            console.log(rules)
            // 有一项失败就是失败了
            const ret = rules.some((rule) => {
                if (rule.required) {
                    // 必填项检验
                    console.log(this.state[field])
                    if (!this.state[field]) {
                        // 检验失败
                        this.setState({ [field + 'Massage']: rule.massage })
                        return true //若有检验失败，返回true
                    }
                }
            })

            if (!ret) {   //没失败检验成功
                this.setState({ [field + 'Massage']: '' })
            }
            return !ret
        }

        // 校验所有字段
        validata = cb => {
            const rets = Object.keys(this.options).map(fidld => this.validaateField(fidld))
            // 如果校验数组红都为true 则检验成功
            const ret = rets.every(v => v === true)
            cb(ret)
        }

        // 判断组件是否被用户点击过
        isFieldTouched = field => !!this.state[field + 'Focus']

        // 获取用户错误信息
        getFieldError = field => this.state[field + 'Massage']

        // 包裹input元素
        getFieldDec = (field, option, InputComp) => {
            this.options[field] = option

            return (
                <div>
                    {/* 克隆元素 */}
                    {React.cloneElement(InputComp, {
                        name: field,  // 修改属性
                        value: this.state[field] || '',
                        onChange: this.handleChange,// Change事件处理
                        onFocus: this.handleFocus   //触摸事件
                    })}
                </div>
            )
        }

        render() {
            return (
                <Comp
                    {...this.props}
                    getFieldDec={this.getFieldDec}
                    value={this.state}
                    validata={this.validata}
                    isFieldTouched={this.isFieldTouched}
                    getFieldError={this.getFieldError}
                />
            )
        }
    }

}


class FormItem extends Component {
    render() {
        return (
            <div className="formItem">
                {this.props.children}
                {
                    this.props.validateStatus === 'error' && (
                        <p style={{ color: 'red' }}>{this.props.help}</p>
                    )
                }
            </div>
        )
    }
}

class Input extends Component {
    render() {
        return (
            <div>
                {/* 前缀图标 */}
                {this.props.prefix}
                <input {...this.props} />
            </div>
        )
    }
}


@kFormCreate
class KFormSample extends Component {

    onSubmit = () => {
        console.log(this.props.value)
        this.props.validata((isValid) => {
            if (isValid) {
                alert('成功')
            }
        })
    }

    render() {
        const { getFieldDec, isFieldTouched, getFieldError } = this.props

        var userNameError = isFieldTouched('uname') && getFieldError('uname')
        var passwordError = isFieldTouched('pwd') && getFieldError('pwd')

        return (
            <div>
                <FormItem
                    validateStatus={userNameError ? 'error' : ''}
                    help={userNameError || ''}
                >
                    {
                        getFieldDec('uname', {
                            rules: [{ required: true, massage: '请填写用户名' }]
                        }, <Input type="text" prefix={'前缀'} />)
                    }
                </FormItem> 
                <FormItem
                    validateStatus={passwordError ? 'error' : ''}
                    help={passwordError || ''}
                >
                    {
                        getFieldDec('pwd', {
                            rules: [{ required: true, massage: '请填写用户名' }]
                        }, <Input type="password" prefix={'前缀'} />)
                    }
                </FormItem>
                <button onClick={() => this.onSubmit()}>登陆</button>
            </div>
        )
    }
}
export default KFormSample